package com.smartpro.mis.modular.business.service;

import com.smartpro.mis.modular.business.neo4jEntity.*;
import com.smartpro.mis.modular.system.dao.MovieRepository;
import com.smartpro.mis.modular.system.dao.N4jProductRepository;
import com.smartpro.mis.modular.system.dao.N4jUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class N4jUserService {

    private final static Logger LOG = LoggerFactory.getLogger(N4jUserService.class);
	private final N4jUserRepository n4jUserRepository;
	public N4jUserService(N4jUserRepository n4jUserRepository) {
		this.n4jUserRepository = n4jUserRepository;
	}

	private Map<String, Object> toD3Format(Collection<N4jUser> n4jUsers) {
		List<Map<String, Object>> nodes = new ArrayList<>();
		List<Map<String, Object>> rels = new ArrayList<>();
		int i = 0;
		Iterator<N4jUser> result = n4jUsers.iterator();
		while (result.hasNext()) {
			N4jUser n4jUser = result.next();
			nodes.add(map("userID", n4jUser.getUserID(), "label", "n4jUser"));
			int target = i;
			i++;
			for (UserProductRelationship userProductRelationship : n4jUser.getUserProductRelationship()) {
				Map<String, Object> n4jProduct = map("productID", userProductRelationship.getN4jProduct().getProductID(), "label", "n4jProduct");
				int source = nodes.indexOf(n4jProduct);
				if (source == -1) {
					nodes.add(n4jProduct);
					source = i++;
				}
				rels.add(map("source", source, "target", target));
			}
		}
		return map("nodes", nodes, "links", rels);
	}

	private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put(key1, value1);
		result.put(key2, value2);
		return result;
	}

    @Transactional(readOnly = true)
    public N4jUser findByUserID(int userID) {
        N4jUser result = n4jUserRepository.findByUserID(userID);
        return result;
    }



	@Transactional(readOnly = true)
	public Map<String, Object>  graph(int limit) {
		Collection<N4jUser> result = n4jUserRepository.graph(limit);
		return toD3Format(result);
	}
}
